package com.gf.gf_data.sys.filter;

import com.gf.gf_data.util.JWTUtil;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * JWT 过滤器
 *
 * Created by Eternal_L on 2018/1/9.
 */
@WebFilter(filterName = "jwtAuthorizeFilter",
        urlPatterns = {"/user/**", "/kd/**"})
public class JWTAuthorizeFilter implements Filter {

    private static final Logger log = LoggerFactory.getLogger(JWTAuthorizeFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("execute-------------JWTAuthorizeFilter -> init");
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, filterConfig.getServletContext());
    }

    /**
     * 验证token
     *
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        log.info("execute-------------JWTAuthorizeFilter -> doFilter");

        HttpServletRequest httpRequest = (HttpServletRequest)request;
        String auth = httpRequest.getHeader(JWTUtil.HEADER_MARK);
        int tokenTypeLen = JWTUtil.TOKEN_TYPE.length();
//        auth = JWTUtil.TOKEN_TYPE + "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1bmlxdWVfbmFtZSI6Iis4NjE4MzIyNzkyMTQzIiwidXNlcl9pZCI6IjE1IiwiZXhwIjoxNTE1NTc3Njk3LCJuYmYiOjE1MTU1NzQwOTd9.SXEPXOvC0yNXDx5voSlN3OlYtU_WR6nVl2Kwj9__sfI";
        log.info("auth = " + auth);
        // 判断Authorization值长度
        if ((auth != null) && (auth.length() > (tokenTypeLen + 1)))
        {
            String headStr = auth.substring(0, tokenTypeLen).toLowerCase();
            if (headStr.compareTo(JWTUtil.TOKEN_TYPE) == 0)
            {
                auth = auth.substring(tokenTypeLen, auth.length());
                // 判断JWT解析是否成功
                Claims claims = JWTUtil.parseJWT(auth, JWTUtil.getBase64SecretKey());
                if ( claims != null)
                {
                    log.info("The token is verified successfully. Account :  " + claims.get(JWTUtil.UNIQUE_NAME_KEY));
                    // 创建新的accessToken
                    String tokenStr = JWTUtil.createJWT(
                            claims.get(JWTUtil.UNIQUE_NAME_KEY).toString(),
                            claims.get(JWTUtil.USER_ID).toString(),
                            JWTUtil.TTL_MILLIS,
                            JWTUtil.getBase64SecretKey());

                    // 将accessToken放入request
                    request.setAttribute(JWTUtil.REQ_TOKEN_MARK, tokenStr);

                    chain.doFilter(request, response);
                    return;
                }
            }
        }
        // 验证未通过
        log.info("Tips : --------->>验证未通过-----");
        request.getRequestDispatcher("/oauth/failure").forward(request, response);
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }
}
